package org.waterbook;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FListActivity extends ListActivity {
	private String currentPath;
	private List<Map<String, Object>> list;
	private SimpleAdapter adapter;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getIntent().getExtras();
		currentPath = bundle.getString("path");
		list = new ArrayList<Map<String, Object>>();
		adapter = new SimpleAdapter(this, list, R.layout.lineoflist,
				new String[] { "img", "name", "size" }, new int[] { R.id.img,
						R.id.name, R.id.size });
		setListAdapter(adapter);
		buildData();
	}

	private void buildData() {
		list.clear();
		File filepath = new File(currentPath);
		String[] files = filepath.list();
		Map<String, Object> map;
		map = new HashMap<String, Object>();
		map.put("img", android.R.drawable.sym_contact_card);
		map.put("name", "..");
		list.add(map);
		if (files != null) {
			for (String file : files) {
				map = new HashMap<String, Object>();
				File tfile = new File(currentPath + "/" + file);
				if (tfile.isDirectory()) {
					map.put("img", android.R.drawable.sym_contact_card);
					list.add(1, map);
				} else {
					map.put("img", android.R.drawable.stat_notify_sdcard);
					map.put("name", file);
					long size = tfile.length();
					map.put("size", size/1000 + "kb");
					list.add(map);
				}
				map.put("name", file);

			}
		}

		adapter.notifyDataSetChanged();

	}

	private String setPath(String subPath) {
		if (subPath.equals("..")) {
			File parent = new File(currentPath).getParentFile();
			if (parent != null) {
				currentPath = parent.getAbsolutePath();
				buildData();
			}
			return null;
		}
		String child = currentPath + "/" + subPath;
		if (new File(child).isDirectory()) {
			currentPath = child;
			buildData();
		} else
			return child;
		return null;

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		TextView name = (TextView) v.findViewById(R.id.name);
		String filePath = setPath(name.getText().toString());
		if (filePath != null) {
			WaterBookActivity.open(filePath);
			this.finish();
		}
	}

}
